package com.syaccp.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.pagehelper.PageInfo;
import com.syaccp.exception.CrmebException;
import com.syaccp.model.OrderDetail;
import com.syaccp.model.OrderInfo;
import com.syaccp.model.OrderOperRecord;
import com.syaccp.model.TOrderDetail;
import com.syaccp.service.OrderInfoService;
import com.syaccp.service.OrderOperRecordService;
import com.syaccp.service.TOrderDetailService;
import com.syaccp.utils.OrderRelatedUtil;
import com.syaccp.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;


/**
 * 订单信息操作控制器
 *
 * @author Lyh
 * @since 2023-07-15 10:27:55
 */
@RestController
@CrossOrigin
@RequestMapping("/api/orderInfo")
@Api(tags = "订单信息控制器")
public class OrderInfoController {

    @Resource
    OrderInfoService orderInfoService;

    @Resource
    TOrderDetailService TOrderDetailService;

    @Resource
    OrderOperRecordService orderOperRecordService;


    @ApiOperation(value = "分页获取订单详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "order", value = "查询条件对象"),
            @ApiImplicitParam(name = "index", value = "当前页")
    })
    @GetMapping(value = "/getOrderInfoByPage")
    public Result<PageInfo<OrderInfo>> queryOrderInfoByPage(@RequestParam Map<String, Object> map) {
        PageInfo<OrderInfo> orderInfoPageInfo = orderInfoService.queryOrderInfoByPage(
                JSON.parseObject((String) map.get("orderInfo"), OrderInfo.class),
                Integer.parseInt(String.valueOf(map.get("index"))));
        return Result.success(orderInfoPageInfo);
    }

    @ApiOperation(value = "根据订单id删除逻辑删除订单信息")
    @ApiImplicitParam(name = "orderId", value = "订单id")
    @DeleteMapping(value = "/deleteOrderById/{orderId}")
    public Result<Integer> deleteOrderInfoById(@PathVariable Integer orderId) {
        return Result.success(orderInfoService.deleteOrderInfoById(orderId));
    }

    @ApiOperation(value = "上传订单和任务图片")
    @ApiImplicitParam(name = "files", value = "数据流数组")
    @PostMapping(value = "/uploadFile")
    public Result<Integer> orderUploadFile(MultipartFile[] files) {
        System.out.println("--------------uploadFile------------");
        if (ObjectUtils.isNotEmpty(files)) {
            for (MultipartFile file : files) {
                System.out.println(file.getOriginalFilename());
                Integer integer = OrderRelatedUtil.fileUpload(file);
                if (integer != 1) throw new CrmebException("文件上传失败!");
            }
        }
        return Result.success();
    }

    @ApiOperation(value = "新增订单信息和对应任务信息")
    @ApiImplicitParam(name = "orderInfo", value = "订单信息对象")
    @PostMapping(value = "/insertOrderData")
    public Result<Integer> insertOrderData(@RequestBody OrderInfo orderInfo) {
        OrderInfo infoData = OrderRelatedUtil.handleOrderInfoData(orderInfo);
        orderInfoService.insertOrderInfo(infoData);
        StringBuilder content = new StringBuilder("创建订单成功，订单号为：" + orderInfo.getOrderNo());
        if (infoData.getOrderDetailList().size() > 0) {
            content.append(",且订单携带了").append(infoData.getOrderDetailList().size()).append("个任务,任务编号分别为：");
            List<TOrderDetail> orderDetails = OrderRelatedUtil.handleOrderDetailData(infoData);
            orderDetails.forEach(item -> {
                TOrderDetailService.insertOrderDetail(item);
                content.append(item.getTaskNo()).append("  ");
            });
        }
        orderOperRecordService.insertOrderRecord(new OrderOperRecord(infoData.getId(), content.toString()));
        return Result.success();
    }

    @ApiOperation(value = "根据订单id查询订单信息")
    @ApiImplicitParam(name = "orderId", value = "订单ID")
    @GetMapping(value = "/getOrderInfoById/{orderId}")
    public Result<OrderInfo> queryOrderInfoById(@PathVariable Integer orderId) {
        return Result.success(orderInfoService.queryOrderInfoByOrderId(orderId));
    }

    @ApiOperation(value = "根据订单id查询该订单的任务信息")
    @ApiImplicitParam(name = "orderId", value = "订单ID")
    @GetMapping(value = "/getOrderDetailByOrderId/{orderId}")
    public Result<List<TOrderDetail>> queryOrderDetailByOrderId(@PathVariable Integer orderId) {
        List<TOrderDetail> orderDetails = TOrderDetailService.queryOrderDetailByOrderId(orderId);
        return Result.success(orderDetails);
    }

    @ApiOperation(value = "新增任务信息")
    @ApiImplicitParam(name = "orderDetail", value = "任务对象")
    @PostMapping(value = "/insertTaskInfo")
    public Result<Integer> insertTaskInfo(@RequestBody TOrderDetail orderDetail) {
        if (StringUtils.isNotBlank(orderDetail.getImage())) {
            orderDetail.setImage("http://127.0.0.1:8081/uploadFiles/" + orderDetail.getImage());
        }
        TOrderDetailService.insertOrderDetail(orderDetail);
        String content = "订单新增一项任务,任务编号为：" + orderDetail.getTaskNo();
        orderOperRecordService.insertOrderRecord(new OrderOperRecord(orderDetail.getOrderId(), content));
        return Result.success(orderDetail.getId());
    }

    @ApiOperation(value = "修改任务信息")
    @ApiImplicitParam(name = "orderDetail", value = "任务对象")
    @PutMapping(value = "/updateTaskInfo")
    public Result<Integer> updateTaskInfo(@RequestBody TOrderDetail orderDetail) {
        String content = "该订单下编号为：" + orderDetail.getTaskNo() + "的任务被修改";
        orderOperRecordService.insertOrderRecord(new OrderOperRecord(orderDetail.getOrderId(), content));
        return Result.success(TOrderDetailService.updateOrderDetail(orderDetail));
    }

    @ApiOperation(value = "根据任务id逻辑删除任务信息")
    @ApiImplicitParam(name = "taskId", value = "任务ID")
    @DeleteMapping(value = "/deleteOrderTask/{taskId}")
    public Result<Integer> deleteOrderTask(@PathVariable Integer taskId) {
        TOrderDetail orderDetail = TOrderDetailService.queryOrderDetailById(taskId);
        String content = "该订单下编号为：" + orderDetail.getTaskNo() + "的任务被删除";
        orderOperRecordService.insertOrderRecord(new OrderOperRecord(orderDetail.getOrderId(), content));
        return Result.success(TOrderDetailService.deleteOrderDetail(taskId));
    }

    @ApiOperation(value = "订单支付尾款")
    @ApiImplicitParam(name = "orderInfo", value = "订单对象")
    @PutMapping(value = "/payMoneyAboutOrder")
    public Result<Integer> payMoneyAboutOrder(@RequestBody OrderInfo orderInfo) {
        String content = "订单进行一笔支付操作,支付成功,支付金额为：￥" + orderInfo.getPayMoney() + ",待支付金额为：￥" + orderInfo.getPayment();
        orderOperRecordService.insertOrderRecord(new OrderOperRecord(orderInfo.getId(), content));
        return Result.success(orderInfoService.payMoney(orderInfo));
    }

    @ApiOperation(value = "任务支付尾款")
    @ApiImplicitParam(name = "orderDetail", value = "任务对象")
    @PutMapping(value = "/payMoneyAboutTask")
    public Result<Integer> payMoneyAboutTask(@RequestBody TOrderDetail orderDetail) {
        String content = "编号" + orderDetail.getTaskNo() + "任务进行一笔支付操作,支付金额为：￥" + orderDetail.getPayMoney() + ",待支付金额为：￥" + (orderDetail.getPayment() - orderDetail.getPayMoney());
        orderOperRecordService.insertOrderRecord(new OrderOperRecord(orderDetail.getOrderId(), content));
        return Result.success(TOrderDetailService.payMoney(orderDetail));
    }

    @ApiOperation(value = "修改订单和任务方法")
    @ApiImplicitParam(name = "orderInfo", value = "订单对象")
    @PutMapping(value = "/updateOrderAndTask")
    public Result<Integer> updateOrderAndTask(@RequestBody OrderInfo orderInfo) {
        String content = "订单已被修改";
        orderOperRecordService.insertOrderRecord(new OrderOperRecord(orderInfo.getId(), content));
        return Result.success(orderInfoService.updateOrderAndTaskInfo(orderInfo));
    }
}
